<template>
  <div :class="svgClass" @click="setIcon">
    <i v-if="isExternal" :class="icon" :style="{ 'font-size': size + 'px' }" @click="setIcon" />
    <svg
      v-else-if="iconClass"
      :style="{ 'width': size + 'px', 'height': size + 'px' }"
      aria-hidden="true"
      v-on="$listeners"
    >
      <use :xlink:href="icon" />
    </svg>
  </div>
</template>

<script>

export default {
  name: 'SvgIcon',
  props: {
    iconClass: {
      type: String,
      default: ''
    },
    className: {
      type: String,
      default: ''
    },
    size: {
      type: Number,
      default: 18
    }
  },
  computed: {
    isExternal() {
      return this.iconClass && !this.iconClass.includes('.svg')
    },
    svgClass() {
      if (this.className) {
        return 'svg-icon ' + this.className
      } else {
        return 'svg-icon'
      }
    },
    icon() {
      return this.isExternal ? this.iconClass.includes('el-icon') ? this.iconClass : 'el-icon-' + this.iconClass
        : `#icon-${this.iconClass.replace('.svg', '')}`
    }
  },
  methods: {
    setIcon() {
      this.$emit('setIcon', { flag: this.isExternal, icon: this.icon.replace(/^(|#icon-)/, '') })
    }
  }
}
</script>

<style scoped>
.svg-icon {
  fill: currentColor;
  display: inline-flex;
}
</style>
